using System;
using System.Text.RegularExpressions;
using Microsoft.WowAddonStudio.FrameXml.Serialization;

namespace Microsoft.WowAddonStudio.FrameXml.Components.Events.ScriptManager
{
    public class FrameXmlScriptManager : IFrameXmlScriptManager
    {
        private static readonly Regex regex = new Regex(@"(?i)^\s*([A-Za-z_][A-Za-z0-9_]*)?\s*(\(\s*\))?\s*(;)?\s*$");
        private readonly IServiceProvider serviceProvider;
        private readonly IDocumentManager documentManager;

        /// <summary>
        /// Initializes a new instance of the <see cref="FrameXmlScriptManager"/> class.
        /// </summary>
        /// <param name="serviceProvider">The service provider.</param>
        public FrameXmlScriptManager(IServiceProvider serviceProvider)
        {
            if (serviceProvider == null)
                throw new ArgumentNullException("serviceProvider");

            this.serviceProvider = serviceProvider;
            documentManager = new EnvDTEDocumentManager(serviceProvider);
        }

        /// <summary>
        /// Adds the script.
        /// </summary>
        /// <param name="control">The control.</param>
        /// <param name="eventName">Name of the event.</param>
        /// <param name="script">The script.</param>
        public void AddScript(FrameControl control, EventName eventName, string script)
        {
            //Create and show (existing) function
            CreateOrShowFunction(script);
        }

        /// <summary>
        /// Removes the script.
        /// </summary>
        /// <param name="control">The control.</param>
        /// <param name="eventName">Name of the event.</param>
        public void RemoveScript(FrameControl control, EventName eventName)
        {
            //Do nothing because script has already removed from ScriptContainer
        }

        /// <summary>
        /// Creates or shows the function.
        /// </summary>
        /// <param name="eventHandlerCode">The code that handles the event.</param>
        public void CreateOrShowFunction(string eventHandlerCode)
        {
            //Check for function call
            if (regex.Match(eventHandlerCode).Success)
            {
                string eventHandlerName = eventHandlerCode.Replace("();", String.Empty);

                if (!documentManager.DoesFunctionExist(eventHandlerName))
                    documentManager.CreateFunction(eventHandlerName);
                else
                    documentManager.ShowFunction(eventHandlerName);
            }
        }

        /// <summary>
        /// Gets a value indicating whether this instance is valid.
        /// </summary>
        /// <value><c>true</c> if this instance is valid; otherwise, <c>false</c>.</value>
        public bool IsValid
        {
            get { return documentManager.IsValid; }
        }
    }
}